package cn.cnsuh.controller.web.servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @author Magic
 * @create 2020-05-24 8:43
 */
@WebServlet("/fileupServlet")
public class FileupServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 创建一个“硬盘文件条目工厂”对象
        DiskFileItemFactory factory = new DiskFileItemFactory();

        // 设置阀值（默认吞吐量是10240byte：10KB）
        factory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD);

        // 设置临时文件存储的目录(仓库)
        String tmpPath = this.getServletContext().getRealPath("tmp");

        factory.setRepository(new File(tmpPath));

        // 创建核心对象
        ServletFileUpload fileUpload = new ServletFileUpload(factory);
//        fileUpload.setFileSizeMax( 1024 * 1024);

        try {
            // 解析请求
            List<FileItem> fileItems = fileUpload.parseRequest(request);
            for (FileItem fileItem : fileItems) {
                if (fileItem.isFormField()) {
                    // 判断该FileItem是否为一个普通的form元素
                    String fieldName = fileItem.getFieldName(); // 获取字段名
                    // String filedValue = fileItem.getString(); // 获取字段值
                    String fieldValue = fileItem.getString("utf-8"); // 解决乱码
                    System.out.println(fieldName + "=" + fieldValue); // username=zhangsan
                } else {
                    // 是一个文件
					/*
					String fileName = fileItem.getName();
					System.out.println(fileName);
					*/
                    String filePath = this.getServletContext().getRealPath("files") + "\\" + fileItem.getName();
                    fileItem.write(new File(filePath));
                    System.out.println(filePath);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
